import { setToken, getToken } from "@/libs/util";
import uiTool from "@/libs/uiTool";
import userServer from "@/api/system/userServer";

export default {
  state: {
    userName: "",
    avatorImgPath: require("@/assets/images/administrato.png"),
    token: getToken(),
    authorityMenus: [],
    menuList: []
  },
  mutations: {
    setAvator(state, avatorPath) {
      state.avatorImgPath = avatorPath;
    },
    setUserName(state, userName) {
      state.userName = userName;
      localStorage.userName = state.userName;
    },
    setToken(state, token) {
      state.token = token;
      setToken(token);
    },
    setAuthorityMenus(state, menus) {
      state.authorityMenus = menus;
      localStorage.authorityMenus = menus;
    },
    setMenuList(state, menus) {
      state.menuList = menus;
    }
  },
  getters: {
    avatorImgPath: state => state.avatorImgPath,
    userName(state) {
      if (!state.userName) {
        state.userName = localStorage.userName;
      }
      return state.userName;
    },
    menuList: state => state.menuList
  },
  actions: {
    async setAuthorityMenus({ state, commit }) {
      let res = await userServer.authorityMenus();
      let authorityMenus = res.data;
      commit("setAuthorityMenus", JSON.stringify(authorityMenus));

      let mainMenu = uiTool.getRoutes();
      commit("setMenuList", mainMenu.children);
    },
    // 登录
    async handleLogin({ state, commit, dispatch }, userFrom) {
      let promise = new Promise(async (resolve, reject) => {
        let res = await userServer.login(userFrom);

        let token = res.data.token;
        let name = res.data.user.name.trim();

        if (res.data.shop) {
          let shopId = res.data.shop.id;
          commit("shop/setShopId", shopId, { root: true });
        }

        commit("setUserName", name);
        commit("setToken", token);

        // 设置登录权限
        await dispatch("setAuthorityMenus");
        resolve(res);
      });

      return promise;
    },
    // 退出登录
    async handleLogOut({ state, commit }, vue) {
      commit("setToken", "");
      commit("setAuthorityMenus", "[]");
      commit("shop/setShopId", "", { root: true });
      window.location.reload();
    }
  }
};
